//
//  NetworkingTool.m
//  record_plugin
//
//  Created by zqj on 2024/9/10.
//

#import "NetworkingTool.h"
#import "Constant.h"
#import "TTSModel.h"

@interface NetworkingTool()

@property (strong, nonatomic) NSString * serverPath;
@property (strong, nonatomic) NSString * roomID;
@property (strong, nonatomic) NSString * userID;
@property (strong, nonatomic) NSString * avdToken;
@property (strong, nonatomic) NSString * accessToken;
@property (strong, nonatomic) NSString * avdUrl;
@property (strong, nonatomic) NSString *  recordId;
@property (strong, nonatomic) NSMutableArray *  mTaskArr;

@end

@implementation NetworkingTool

+ (instancetype)sharedInstance
{
    static NetworkingTool *networkingTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        networkingTool = [[NetworkingTool alloc] init];
        networkingTool.mTaskArr = [NSMutableArray array];
    });
    return networkingTool;
}

- (void)getAuthTokenWithServerPath:(NSString *)serverPath handler:(void(^)(NSString *accessToken))handler failure:(void(^)( NSError * error))fail{
    self.serverPath = serverPath;
    NSData *data = [@"Dgzq123456" dataUsingEncoding:NSUTF8StringEncoding];
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    NSDictionary *parms = @{@"grant_type":@"password",
                            @"client_id":@"sl-app",
                            @"client_secret":@"ls2021",
                            @"language":@"cn",
                            @"phone":@"15208436506",
                            @"vCode":@"3716",
                            @"password":baseString,
                         };

    NSString *url =  AVDUrlWithParamter(serverPath,@"/auth/oauth/token");//UrlWithParamter(@"/auth/oauth/token");
    WeakSelf;
    [[AFHTTPSessionManager manager] POST:url parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            if([dic[@"code"] intValue] == 200){
                if ([dic[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSString *token = dic[@"data"][@"accessToken"];
                    weakSelf.accessToken = token;
                    weakSelf.customerId =  [dic[@"data"][@"customerId"] intValue];
                    handler(token);
                    NSLog(@"req******* 获取authtoken成功 = %@",token);
                }            
            }else{
                NSLog(@"req******* 获取authtoken失败 msg = %@",dic[@"message"]);
                NSError *err = [NSError errorWithDomain:dic[@"message"] code:[dic[@"code"] intValue] userInfo:nil];
                fail(err);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}


- (void)uploadIdentityImgWithHandler:(void(^)(NSString *firstImgUrl))handler failure:(void(^)( NSError * error))fail{
    UIImage *img = UIImageWithName(@"Id_Card@2x.jpg");
    NSData *imageData = UIImageJPEGRepresentation(img, 0.4);
    NSString *imageBase64Str = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSString *url =  AVDUrlWithParamter(self.serverPath,@"/customer/files/idCardUpload");
    NSDictionary *parms = @{
        @"base64Data":imageBase64Str,
        @"suffix":@"png"
    };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *authorizationHeader = [NSString stringWithFormat:@"Bearer %@",self.accessToken];
    [manager.requestSerializer setValue:authorizationHeader forHTTPHeaderField:@"Authorization"];
    [manager POST:url parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSString *firstImgUrl =  UrlWithParamter(dic[@"url"]);
            NSLog(@"req******* 上传身份证成功 url = %@",firstImgUrl);
            handler(firstImgUrl);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
    
}


- (void)getAVDServerWithHandler:(void(^)(NSString *avdServerUrl))handler failure:(void(^)( NSError * error))fail{
    NSDictionary *parms = @{@"access_token":self.accessToken,
                            @"login_type":@"client",
                         };
    NSString *url =  AVDUrlWithParamter(self.serverPath,@"/customer/api/config");
    //NSString *url = UrlWithParamter(@"/customer/api/config");
    WeakSelf;
    [[AFHTTPSessionManager manager] GET:url parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        
        if([dic[@"code"] intValue] == 200){
            NSString *avdServerUrl = dic[@"map"][@"serverConfig"][@"avdServerUrl"];
            NSLog(@"req******* avdServerUrl = %@",avdServerUrl);
//            avdServerUrl = @"https://cd.nice2meet.cn:7840";//暂时写死成都服务器
            weakSelf.avdUrl = avdServerUrl;
            //[weakSelf getAVDToken:avdServerUrl];
            //[weakSelf getAVDToken:@"https://cd.nice2meet.cn:7820"];
            handler(avdServerUrl);
        }else{
            NSLog(@"req******* 获取avdServerUrl失败 msg = %@",dic[@"message"]);
            NSError *err = [NSError errorWithDomain:dic[@"message"] code:[dic[@"code"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}


- (void)getAVDTokenWithHandler:(void(^)(NSString *avdToken))handler failure:(void(^)( NSError * error))fail{
    NSDictionary *parms = @{@"access_key":@"demo_access",
                            @"secret_key":@"demo_secret",
                         };
    NSString *tokenUrl = AVDUrlWithParamter(self.avdUrl, @"/sdkapi/v2/app/get_token");
    WeakSelf;
    [[AFHTTPSessionManager manager] GET:tokenUrl parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"获取avdtoken = %@",dic);
        if([dic[@"ret"] intValue] == 0){
            NSString *token = dic[@"token"];
            NSLog(@"req******* 获取avdtoken = %@",token);
            weakSelf.avdToken = token;
            //[weakSelf initAVDEng:url token:token];
            handler(token);
        }else{
            NSLog(@"req******* 获取avdtoken失败 code = %@",dic[@"ret"]);
            NSError *err = [NSError errorWithDomain:dic[@"msg"] code:[dic[@"ret"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}


- (void)creteTTSPlayer:(NSString *)roomID handler:(void(^)(NSString *playerID))handler failure:(void(^)( NSError * error))fail{
    self.roomID = roomID;
    NSDictionary *parms = @{@"token":self.avdToken,
                            @"room_id":roomID,
                            @"name":@"tts_player",
                            @"auto_publish_mock_audio":@"true",
                            @"stop_event_notify_delay_time":@"1"
                         };
    NSString *ttsCreateUrl = AVDUrlWithParamter(self.avdUrl,@"/sdkapi/v2/media/create")
    WeakSelf;
    [[AFHTTPSessionManager manager] GET:ttsCreateUrl parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if([dic[@"ret"] intValue] == 0){
            NSString *playerID = dic[@"play_id"];
            weakSelf.playerID = playerID;
            handler(playerID);
            NSLog(@"req******* 创建tts播放起成功 id = %@",playerID);
        }else{
            NSLog(@"req******* 创建tts播放起失败");
            NSError *err = [NSError errorWithDomain:dic[@"msg"] code:[dic[@"ret"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

- (void)playTTS:(NSString *)ttsUrl handler:(void(^)(NSInteger totalTime))handler failure:(void(^)( NSError * error))fail{
    NSDictionary *parms = @{@"token":self.avdToken,
                            @"room_id":self.roomID,
                            @"play_id":self.playerID,
                            @"url":ttsUrl,
                            @"enable_auto_close_stream":@"false"
                         };
    NSString *ttsPlayUrl = AVDUrlWithParamter(self.avdUrl, @"/sdkapi/v2/media/play")
    [[AFHTTPSessionManager manager] POST:ttsPlayUrl parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if([dic[@"ret"] intValue] == 0){
            NSLog(@"req******* tts播放成功");
            NSInteger time = [dic[@"data"][@"duration"] intValue];
            handler(time);
        }else{
            NSLog(@"req******* ts播放失败");
            NSError *err = [NSError errorWithDomain:dic[@"msg"] code:[dic[@"ret"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

- (void)stopTTSPlayerWithHandler:(void(^)(void))handler failure:(void(^)( NSError * error))fail{
    NSDictionary *parms = @{@"token":self.avdToken,
                            @"room_id":self.roomID,
                            @"play_id":self.playerID,
                         };
    NSString *ttsPlayUrl = AVDUrlWithParamter(self.avdUrl, @"/sdkapi/v2/media/stop")
    [[AFHTTPSessionManager manager] POST:ttsPlayUrl parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if([dic[@"ret"] intValue] == 0){
            NSLog(@"req******* tts停止播放成功");
            handler();
        }else{
            NSLog(@"req******* tss停止播放失败");
            NSError *err = [NSError errorWithDomain:dic[@"msg"] code:[dic[@"ret"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}


- (void)audio2TextAsr:(NSString *)path handler:(void(^)(NSString *asrTxt))handler failure:(void(^)( NSError * error))fail{
    NSData *audioData = [NSData dataWithContentsOfFile:path];
    NSString *audioBase64Str = [audioData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSDictionary *parms = @{@"phone":@"15208436506",
                            @"audio":audioBase64Str,
                            @"systemType":@(5)
                         };
    NSString *url =  AVDUrlWithParamter(self.serverPath,@"/customer/audioAction/asr");
    //NSString *url = UrlWithParamter(@"/customer/audioAction/asr");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *authorizationHeader = [NSString stringWithFormat:@"Bearer %@", self.accessToken];
    [manager.requestSerializer setValue:authorizationHeader forHTTPHeaderField:@"Authorization"];
    [manager POST:url parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        
        if([dic[@"code"] intValue] == 200){
            NSString *asrText = dic[@"data"];
            handler(asrText);
            NSLog(@"req******* asr语音转文字成功 = %@",asrText);
        }else{
            NSLog(@"req******* asr语音转文字失败 msg = %@",dic[@"message"]);
            NSError *err = [NSError errorWithDomain:dic[@"message"] code:[dic[@"code"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"req******* asr语音转文字失败 err = %@",error.localizedDescription);
        fail(error);
    }];
}


- (void)text2Tss:(NSString *)text handler:(void(^)(NSString *ttsUrl))handler failure:(void(^)( NSError * error))fail{
    NSDictionary *parms = @{@"phone":@"15208436506",
                            @"req":text,
                            @"systemType":@(5)
                         };
    NSString *url =  AVDUrlWithParamter(self.serverPath,@"/customer/audioAction/tts");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *authorizationHeader = [NSString stringWithFormat:@"Bearer %@", self.accessToken];
    [manager.requestSerializer setValue:authorizationHeader forHTTPHeaderField:@"Authorization"];

    [manager POST:url parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        
        if([dic[@"code"] intValue] == 200){
            NSString *ttsURL = dic[@"data"];
            handler(ttsURL);
            NSLog(@"req******* tts转语音成功 = %@",ttsURL);
        }else{
            NSLog(@"req******* tts转语音失败 msg = %@",dic[@"message"]);
            NSError *err = [NSError errorWithDomain:dic[@"message"] code:[dic[@"code"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

- (void)joinQueue:(NSInteger )productId name:(NSString *)name handler:(void(^)(NSString *roomId))handler failure:(void(^)( NSError * error))fail{
    NSDictionary *parms = @{@"customerType":@(0),
                            @"customerName":name,
                            @"customerId":@(self.customerId),
                            @"productId":@(productId),
                         };
    NSString *url =  AVDUrlWithParamter(self.serverPath,@"/customer/customerQueue/joinQueue");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *authorizationHeader = [NSString stringWithFormat:@"Bearer %@", self.accessToken];
    [manager.requestSerializer setValue:authorizationHeader forHTTPHeaderField:@"Authorization"];
    NSURLSessionTask *task = [manager POST:url parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        
        if([dic[@"code"] intValue] == 0){
            NSString *roomid = dic[@"data"][@"roomNo"];
            NSLog(@"req******* 加入排队成功 房间号 = %@",roomid);
            handler(roomid);
        }else{
            NSLog(@"req******* 加入排队失败 msg = %@",dic[@"message"]);
            NSError *err = [NSError errorWithDomain:dic[@"message"] code:[dic[@"code"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
    [self.mTaskArr addObject:task];
}


- (void)faceDetect:(NSString *)firstFileUrl localImg:(UIImage *)localImg handler:(void(^)(NSInteger code ,double similarity))handler failure:(void(^)( NSError * error))fail{
    //200对比通过 500人脸不在框 600多人在框
    NSData *imageData2 = UIImageJPEGRepresentation(localImg, 0.4);
    NSString *second64 = [imageData2 base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSDictionary *bodyParm =  @{@"firstFile":firstFileUrl,
                                @"secondData":second64,
                                @"phone":@"15208436506",
                                @"systemType":@(5),
                               };
    NSString *faceDetectUrl =  AVDUrlWithParamter(self.serverPath,@"/customer/faceDetect/compareImages");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *authorizationHeader = [NSString stringWithFormat:@"Bearer %@",self.accessToken];
    [manager.requestSerializer setValue:authorizationHeader forHTTPHeaderField:@"Authorization"];
    NSURLSessionTask *task = [manager POST:faceDetectUrl parameters:bodyParm headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               if ([responseObject isKindOfClass:[NSDictionary class]]) {
                   // 请求成功数据处理
                   NSDictionary *dic = (NSDictionary *)responseObject;
                   NSInteger code = [dic[@"code"] intValue];
                   double similarity= 0.00;
                   if (code == 200) {
                       NSDictionary *dataDic = dic[@"data"][0];
                       //NSLog(@"datadic = %@ dic = %@",dataDic,dic);
                       similarity = [dataDic[@"similarity"] doubleValue];
                   }
                   handler(code,similarity);
                   NSLog(@"req******* 人脸对比 code = %d 相似度 = %f",code,similarity);
               }
           }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"req******* 人脸检测请求错误 err = %@", error.localizedDescription);
        fail(error);
    }];
    [self.mTaskArr addObject:task];
}

- (void)startServerRecord:(NSString *)roomID handler:(void(^)(void))handler failure:(void(^)( NSError * error))fail{
    self.roomID = roomID;
    NSDictionary *parms = @{@"token":self.avdToken,
                            @"room_id":self.roomID,
                            @"video_resolution":@"720*1280",
                            @"enable_audio_record":@"true",
                            @"enable_realtime_transcode":@"true",
                         };
    NSString *ttsPlayUrl = AVDUrlWithParamter(self.avdUrl, @"/sdkapi/v2/room/mix_record/start")
    WeakSelf;
    [[AFHTTPSessionManager manager] POST:ttsPlayUrl parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if([dic[@"ret"] intValue] == 0){
            NSLog(@"req******* 服务器录制开启成功");
            weakSelf.recordId = dic[@"record_id"];
            handler();
        }else{
            NSLog(@"req******* 服务器录制开启失败");
            NSError *err = [NSError errorWithDomain:dic[@"msg"] code:[dic[@"ret"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

- (void)stopServerRecordWithHandler:(void(^)(NSString *palyUrl))handler failure:(void(^)( NSError * error))fail{
    NSDictionary *parms = @{@"token":self.avdToken,
                            @"room_id":self.roomID,
                         };
    NSString *ttsPlayUrl = AVDUrlWithParamter(self.avdUrl, @"/sdkapi/v2/room/mix_record/stop")
    [[AFHTTPSessionManager manager] POST:ttsPlayUrl parameters:parms headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if([dic[@"ret"] intValue] == 0){
            NSLog(@"req******* 服务器录制停止成功 dic = %@",dic);
            NSArray *videos = dic[@"data"];
            NSDictionary *infoDic = videos.firstObject;
            handler(infoDic[@"down_url"]);
        }else{
            NSLog(@"req******* 服务器录制停止失败");
            NSError *err = [NSError errorWithDomain:dic[@"msg"] code:[dic[@"ret"] intValue] userInfo:nil];
            fail(err);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

- (void)getTSSListWithCode:(NSString *)code handler:(void(^)(NSMutableArray *ttsArr))handler failure:(void(^)( NSError * error))fail{
    NSMutableArray *mArr = [NSMutableArray array];
    NSDictionary *bodyParm =  @{@"code":code,
                                @"type":@1,
                                @"key":@"4ed703814b74013e03f2706c945454e1b155d0bd01d8781cdf633b5c51cb480f",
                               };
    NSString *faceDetectUrl =  AVDUrlWithParamter(self.serverPath,@"/hiapp/service/srv/setting/getSpeechcraft.srv");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    NSString *authorizationHeader = [NSString stringWithFormat:@"Bearer %@",self.accessToken];
//    [manager.requestSerializer setValue:authorizationHeader forHTTPHeaderField:@"Authorization"];
     [manager POST:faceDetectUrl parameters:bodyParm headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               if ([responseObject isKindOfClass:[NSDictionary class]]) {
                   // 请求成功数据处理
                   NSDictionary *dic = (NSDictionary *)responseObject;
                   if([dic[@"returnCode"] intValue] == 0){
                       NSLog(@"req******* 获取话术列表成功");
                       NSArray *videos = dic[@"data"];
                       for (NSDictionary *dic in videos) {
                           TTSModel *model = [[TTSModel alloc]initWihtDic:dic];
                           [mArr addObject:model];
                       }
                       handler(mArr);
                   }else{
                       NSLog(@"req******* 获取话术列表失败");
                       NSError *err = [NSError errorWithDomain:dic[@"returnMessage"] code:[dic[@"returnCode"] intValue] userInfo:nil];
                       fail(err);
                   }
               }
           }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"req******* 获取话术列表失败 err = %@", error.localizedDescription);
        fail(error);
    }];
}

- (void)cancleReq{
    [self.mTaskArr enumerateObjectsUsingBlock:^(NSURLSessionTask  *task, NSUInteger idx, BOOL * _Nonnull stop) {
        [task cancel];
        if (stop) {
            [self.mTaskArr removeAllObjects];
        }
    }];
    NSLog(@"销毁所有restFul请求");
}

@end
